<?php

namespace app\shop\model\welfare;

use app\common\model\welfare\Officer as OfficerModel;
use app\proxy\model\proxy\Region;
use app\shop\model\supplier\Supplier as SupplierModel;

class Officer extends OfficerModel
{

    public function getList($params)
    {
        $model = $this;

        $model = $this->setWhere($model, $params);

        // 查询列表数据
        $list =  $model->with(["qr_code", 'bg_image', 'supplier'])->where('is_delete', '=', '0')
            ->withAttr('proxy_name', function ($value, $data) {
                return Region::getProxyName($data, 0);
            })->append(['proxy_name'])
            ->order(['create_time' => 'desc'])
            ->paginate($params);
        return $list;
    }

    public function setWhere($model, $data)
    {
        if (isset($data['keywords']) && $data['keywords']) {
            $model = $model->where('name', 'like', '%' . $data['keywords'] . '%');
        }
        if (isset($data['create_time']) && $data['create_time'] != '') {
            $sta_time = array_shift($data['create_time']);
            $end_time = array_pop($data['create_time']);
            $model = $model->whereBetweenTime('create_time', $sta_time, date('Y-m-d 23:59:59', strtotime($end_time)));
        }
        if (isset($data['is_audit'])) {
            $model = $model->where('is_audit', $data['is_audit']);
        }

        $map = [];

        if (isset($data['province_id']) && $data['province_id']) {
            $model = $model->where('province_id', '=', $data['province_id']);
        }
        if (isset($data['city_id']) && $data['city_id']) {
            $model = $model->where('city_id', '=', $data['city_id']);
        }
        if (isset($data['region_id']) && $data['region_id']) {
            $model = $model->where('region_id', '=', $data['region_id']);
        }

        if (isset($data['search']) && $data['search']) {
            $map[] = ['name', 'like', '%' . trim($data['search']) . '%'];
        }

        if($map){
            $shop_supplier_ids = (new SupplierModel())->where($map) -> column('shop_supplier_id');
            $model = $model->where('shop_supplier_id', 'in',$shop_supplier_ids);
        }


        return $model;
    }

    /**
     *修改
     * edit
     * @param $data
     * @return bool
     * @Author kevin
     * @date 2024/5/22 14:33
     */
    public function edit($data)
    {
        // 开启事务
        $this->startTrans();
        try {
            $this->save($data);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }
}